import socket
import struct
import os
import fpm_pb2 as fpm
import time
import logging
import platform
import json
import fcntl, termios, array
import thread

logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler('/tmp/fpmlog')
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(created).6f - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

def on_new_client(conn, addr):
    while True:
        print conn.getpeername()
        data = conn.recv(4)
        d = bytearray(data)
        x, y, size = struct.unpack('>ccH', d)
        body = conn.recv(size - 4)
        m = fpm.Message()
        m.ParseFromString(body)
        # logger.info(conn.getpeername())
        if (conn.getpeername()[0] == '11.0.0.34'):
            logger.info(m)
        print m
        if m.HasField('add_route'):
            print 'add_route'

def fpm_server():
    addr = ('0.0.0.0', 2620)
    s = socket.socket()
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(addr)
    s.listen(10)

    while True:
        c, addr = s.accept()
        print 'new connection from'
        thread.start_new_thread(on_new_client, (c, addr))
    s.close()

if __name__ == '__main__':
    fpm_server()